<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="承&nbsp;&nbsp;租&nbsp;&nbsp;人" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入承租人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="到期提醒">
              <el-select v-model="queryParams.expirationReminder" placeholder="请选择到期提醒" clearable>
                <el-option v-for="dict in park_expiration_reminder" :key="dict.value" :label="dict.label" :value="dict.value"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="缴租频次" prop="frentPaymentFrequency">
              <el-select v-model="queryParams.frentPaymentFrequency" placeholder="请选择缴租频次" clearable>
                <el-option v-for="dict in park_frent_payment_frequency" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否收取" prop="contractStatus">
              <el-select v-model="queryParams.collect" clearable>
                <el-option v-for="dict in is_collect" :key="dict.value" :label="dict.label" :value="dict.value"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="名称">
              <el-input v-model="queryParams.parkName" placeholder="请输入名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="楼&nbsp;&nbsp;栋&nbsp;&nbsp;号">
              <el-input v-model="queryParams.towerNumber" placeholder="请输入楼栋号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="房&nbsp;&nbsp;间&nbsp;&nbsp;号">
              <el-input v-model="queryParams.roomNumber" placeholder="请输入房间号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="24" style="text-align: right">
            <el-button type="warning" icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->
        </el-row>
      </template>

      <el-table v-loading="loading" :data="tenantList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="false" />
        <el-table-column label="园区建筑信息主键" align="center" prop="parkBuildingId" v-if="false" />
        <el-table-column label="序号" align="center">
          <template #default="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column label="租赁人" align="center" prop="name" />
        <el-table-column label="缴租频次" align="center" prop="frentPaymentFrequency">
          <template #default="scope">
            <dict-tag :options="park_frent_payment_frequency" :value="scope.row.frentPaymentFrequency" />
          </template>
        </el-table-column>
        <el-table-column label="联系方式" align="center" prop="contactInformation" />
        <el-table-column label="应收租金(元)" align="center" prop="rentReceivable" />
        <el-table-column label="是否收取" align="center" prop="collect">
          <template #default="scope">
            <dict-tag :options="is_collect" :value="scope.row.collect" />
          </template>
        </el-table-column>
        <el-table-column label="实收日期" align="center" prop="paidInTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.paidInTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="项目名称" align="center" prop="parkName" />
        <el-table-column label="楼栋号" align="center" prop="towerNumber" />
        <el-table-column label="房间号" align="center" prop="roomNumber" />
        <el-table-column label="建筑面积(㎡)" align="center" prop="floorArea" />
        <el-table-column label="到期提醒" align="center" prop="expirationReminder" />
        <el-table-column label="操作" align="center" width="120" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleOpenForm('update', scope.row.parkBuildingId, scope.row.id)"> 编辑 </el-button>
            <el-button link type="primary" @click="handleOpenForm('detail', scope.row.parkBuildingId, scope.row.id)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <formDialog ref="tenantFormRef" @success="getList" />
  </div>
</template>

<script setup name="Tenant" lang="ts">
import { listTenant, getTenant, delTenant, addTenant, updateTenant } from '@/api/zichanguanli/parktenant/index';
import { TenantVO, TenantQuery, ParkTenantForm } from '@/api/zichanguanli/parktenant/types';
import { BuildingVO, BuildingQuery, BuildingForm } from '@/api/zichanguanli/parkbuilding/types';
import { listFoundationInfoList } from '@/api/zichanguanli/foundationInfo/index';
import { FoundationInfoVO } from '@/api/zichanguanli/foundationInfo/types';

import formDialog from './form.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { park_surrender_tenancy_status, park_frent_payment_frequency, park_expiration_reminder, is_collect } = toRefs<any>(
  proxy?.useDict('park_surrender_tenancy_status', 'park_frent_payment_frequency', 'park_expiration_reminder', 'is_collect')
);

const tenantList = ref<TenantVO[]>([]);
const foundationInfoList = ref<FoundationInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const tenantFormRef = ref();

const handleOpenForm = (type: string, id?: string | number) => {
  tenantFormRef.value.open(type, id);
};
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ParkTenantForm = {
  id: undefined,
  parkBuildingId: undefined,
  name: undefined,
  frentPaymentFrequency: undefined,
  rents: undefined,
  contactInformation: undefined,
  startTime: undefined,
  endTime: undefined,
  remark: undefined,
  leaseTerm: undefined,
  propertyCostStandard: undefined,
  attachments: undefined,
  surrenderTenancyStatus: undefined,
  rentOutTime: undefined
};

const buildingForm: BuildingForm = {
  id: undefined,
  parkFoundationInfoId: undefined,
  towerNumber: undefined,
  floor: undefined,
  roomNumber: undefined,
  floorArea: undefined,
  roomEnvironment: undefined,
  roomState: undefined,
  contactPerson: undefined,
  remark: undefined,
  attachments: undefined
};
const data = reactive<PageData<ParkTenantForm, TenantQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    parkName: undefined,
    collect: undefined,
    expirationReminder: undefined,
    frentPaymentFrequency: undefined,
    name: undefined,
    roomNumber: undefined,
    towerNumber: undefined
  },
  rules: {
    id: [{ required: true, message: '主键不能为空', trigger: 'blur' }],
    parkBuildingId: [{ required: true, message: '园区建筑信息主键不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '承租人不能为空', trigger: 'blur' }],
    frentPaymentFrequency: [{ required: true, message: '缴租频次不能为空', trigger: 'change' }],
    rents: [{ required: true, message: '租金不能为空', trigger: 'blur' }],
    startTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
    endTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],
    attachments: [{ required: true, message: '租赁附件不能为空', trigger: 'blur' }],
    surrenderTenancyStatus: [{ required: true, message: '退租状态不能为空', trigger: 'change' }],
    rentOutTime: [{ required: true, message: '退租时间不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询园区租户列表 */
const getList = async () => {
  loading.value = true;
  const res = await listTenant(queryParams.value);
  tenantList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  tenantFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  (queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    parkName: undefined,
    collect: undefined,
    expirationReminder: undefined,
    frentPaymentFrequency: undefined,
    name: undefined,
    roomNumber: undefined,
    towerNumber: undefined
  }),
    handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: TenantVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加园区租户';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: TenantVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getTenant(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改园区租户';
};

/** 提交按钮 */
const submitForm = () => {
  tenantFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateTenant(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addTenant(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: TenantVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('确定删除所选的信息吗？').finally(() => (loading.value = false));
  await delTenant(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    '/zichanguanli/parktenant/export',
    {
      ...queryParams.value
    },
    `租户信息.xlsx`
  );
};

/** 查询园区基础信息列表 */
const getParkList = async () => {
  loading.value = true;
  const res = await listFoundationInfoList();
  foundationInfoList.value = res.data;
  total.value = res.total;
  loading.value = false;
};

onMounted(() => {
  getList();
});
</script>
<style scoped>
/* el-table 列数据为空自动显示 -- */
::v-deep .el-table .el-table__body td .cell:empty::after,
.el-table .el-table__body td .cell > span:empty::after,
.el-table .el-table__body td .cell .approval:empty::after,
.el-table .el-table__body td .cell div:empty::after,
.el-table .el-table__body td .cell .line-limit-length:empty::after {
  content: '-';
}
</style>
